package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageAll;
import com.itheima.pojo.Student;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServicelmpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageAll findClazzs(String name, Integer page, Integer pageSize, LocalDateTime begin, LocalDateTime end) {
        //分页插件
        PageHelper.startPage(page, pageSize);
        //数据库查询数据返回list
        List<Clazz> list = clazzMapper.findClazzs(name, begin, end);
        //强转为Page
        Page<Clazz> clazzPage = (Page<Clazz>) list;
        //new PageClazz实体类对象插入数据
        return new PageAll(clazzPage.getTotal(), clazzPage.getResult());
    }

    @Override
    public List<Clazz> findClazzList() {
        List<Clazz> clazzList = clazzMapper.findClazzList();
        return clazzList;
    }

    @Override
    public void deleteClazz(Integer id) {
        //1.判断 班级里是否有学生，如果有学生的话，那么不允许删除班级。
        //1.1.根据班级id查询学生表
        List<Student> studentList = clazzMapper.FindStudent(id);
        //1.2.判断集合是否为空
        if (!ObjectUtils.isEmpty(studentList)) {
            //不为空
            throw new RuntimeException("班级不为空！不允许删除！");
        }
        //为空，删除
        clazzMapper.deleteClazz(id);
    }

    @Override
    public void addClazz(Clazz clazz) {
        clazzMapper.addClazz(clazz);
    }

    @Override
    public void updateClazz(Clazz clazz) {
        clazzMapper.updateClazz(clazz);
    }

    @Override
    public Clazz getClazzById(Integer id) {

        return clazzMapper.getClazzById(id);
    }
}
